package gold.digger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC567 {


    public boolean checkInclusion(String s1, String s2) {
        Map<Character, Integer> need = new HashMap<>();
        Map<Character, Integer> window = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            char ch = s1.charAt(i);
            mapAdd(need, ch);
        }

        int left = 0, right = 0, valid = 0;
        while (right < s2.length()) {
            char ch = s2.charAt(right);
            right++;

            if (need.containsKey(ch)) {
                // cause window only contain useful chars
                mapAdd(window, ch);
                // if current slide window already contains enough char
                if (need.get(ch).intValue() == window.get(ch).intValue()) {
                    valid++;
                }
            }

            // update window
            while (right - left >= s1.length()) {
                if (valid == need.size()) {
                    return true;
                }

                char leftCh = s2.charAt(left);
                left++;

                // shrunk current window
                if (need.containsKey(leftCh)) {
                    if (need.get(leftCh).intValue() == window.get(leftCh).intValue()) {
                        valid--;
                    }
                    window.put(leftCh, window.get(leftCh) - 1);
                    if (window.get(leftCh) <= 0) {
                        System.out.println(leftCh + " -> " + window.get(leftCh));
                    }
                }
            }
        }

        return false;
    }

    public void mapAdd(Map<Character, Integer> count, char ch) {
        if (count.containsKey(ch)) {
            count.put(ch, count.get(ch) + 1);
        } else {
            count.put(ch, 1);
        }
    }

    public static void main(String[] args) {
        LC567 an = new LC567();
        System.out.println(an.checkInclusion("ab", "eidbaooo"));
    }

}
